import json
from datetime import datetime


class Room:
    def __init__(self, floor, number, price, status, room_type):
        self.floor = floor
        self.number = number
        self.price = price
        self.status = status
        self.room_type = room_type
        self.booking_history = []  # 历史预订记录

    def __str__(self):
        return f"楼层: {self.floor}, 房间号: {self.number}, 房价: {self.price}, 状态: {self.status}, 类型: {self.room_type}"

    def add_booking(self, date_time):
        self.booking_history.append(date_time)
        if self.status != '有人':
            self.status = '有人'

    @staticmethod
    def from_json(data):
        return Room(data['floor'], data['number'], data['price'], data['status'], data['room_type'])


class Hotel:
    def __init__(self, filename='rooms.json'):
        self.rooms = []
        self.room_types = {
            '单人间': 98,
            '双人间': 128,
            '标准间': 148,
            '商务房': 288,
            '豪华包': 688
        }
        self.load_rooms(filename)

    def load_rooms(self, filename):
        try:
            with open(filename, 'r', encoding='utf-8') as file:
                room_datas = json.load(file)
                self.rooms = [Room.from_json(room_data) for room_data in room_datas]
        except FileNotFoundError:
            print(f"{filename} 文件未找到。")

    def save_rooms(self, filename='rooms.json'):
        with open(filename, 'w', encoding='utf-8') as file:
            rooms_to_save = [{
                'floor': room.floor, 'number': room.number, 'price': room.price,
                'status': room.status, 'room_type': room.room_type,
                'booking_history': room.booking_history
            } for room in self.rooms]
            json.dump(rooms_to_save, file, ensure_ascii=False, indent=4)

    def view_rooms(self):
        for room in self.rooms:
            print(room)

    def find_room_by_number(self, number):
        for room in self.rooms:
            if room.number == number:
                return room
        return None

    def book_room(self, number):
        room = self.find_room_by_number(number)
        if room and room.status == '空闲':
            # 获取当前日期和时间
            current_datetime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            room.add_booking(current_datetime)
            self.save_rooms()
            print(f"房间 {number} 已成功预订于 {current_datetime}。")
        else:
            print("房间不可用或已被预订。")

    def check_out(self, number):
        room = self.find_room_by_number(number)
        if room and room.status == '有人':
            room.status = '空闲'
            print(f"房间 {number} 已退订，现在可以重新预定。")
            self.save_rooms()
        else:
            print("房间不存在或无需退订。")

    def modify_price(self, room_type, new_price):
        if room_type in self.room_types:
            original_price = self.room_types[room_type]
            self.room_types[room_type] = new_price
            for room in self.rooms:
                if room.room_type == room_type:
                    room.price = new_price
            print(f"所有{room_type}的房价已从{original_price}更新为{new_price}。")
            self.save_rooms()
        else:
            print("房间类型不存在。")

    def view_booking_history(self, number):
        room = self.find_room_by_number(number)
        if room:
            if room.booking_history:
                print(f"房间 {number} 的历史预订记录:")
                for index, date in enumerate(room.booking_history, 1):
                    print(f"{index}. {date}")
            else:
                print(f"房间 {number} 没有历史预订记录。")
        else:
            print("房间不存在。")

    def exit_system(self):
        self.save_rooms()
        print("退出系统。再见!")
        exit()


# 示例：创建酒店对象
hotel = Hotel()

# 演示功能
while True:
    try:
        print("\n欢迎使用飞思酒店管理系统V1.0")
        print("1: 查看所有房间")
        print("2: 预订房间")
        print("3: 退订房间")
        print("4: 修改价格")
        print("5: 退出系统")
        print("6: 查看房间历史预订记录")
        choice = input("输入您的选择: ")

        if choice == '1':
            hotel.view_rooms()
        elif choice == '2':
            room_number = input("输入要预订的房间号：")
            if room_number.isdigit():
                hotel.book_room(int(room_number))
            else:
                print("房间号必须是数字。")
        elif choice == '3':
            room_number = input("输入要退房的房间号: ")
            if room_number.isdigit():
                hotel.check_out(int(room_number))
            else:
                print("房间号必须是数字。")
        elif choice == '4':
            room_type = input("输入房间类型: ")
            new_price = input("输入新价格: ")
            if new_price.isdigit():
                hotel.modify_price(room_type, int(new_price))
            else:
                print("价格必须是数字。")
        elif choice == '5':
            confirm = input("您确定要退出系统吗？(y/n): ")
            if confirm.lower() == 'y':
                hotel.exit_system()
        elif choice == '6':
            room_number = input("输入要查看历史预订记录的房间号：")
            if room_number.isdigit():
                hotel.view_booking_history(int(room_number))
            else:
                print("房间号必须是数字。")
        else:
            print("无效选择。请重试。")
    except Exception as e:
        print(f"发生错误：{e}。请重试。")
